package com.mes.loco.aps.server.controller.sfc;

import com.iplant.aps.controller.BaseController;
import com.iplant.aps.service.SFCService;
import com.iplant.aps.service.po.ServiceResult;
import com.iplant.aps.service.po.bms.BMSEmployee;
import com.iplant.aps.service.po.excel.ExcelData;
import com.iplant.aps.service.po.mss.MSSBOMItem;
import com.iplant.aps.service.po.sfc.SFCOutMaterialConfig;
import com.iplant.aps.service.po.sfc.SFCOutMaterialConfigItem;
import com.iplant.aps.service.utils.CloneTool;
import com.iplant.aps.service.utils.Configuration;
import com.iplant.aps.service.utils.StringUtils;
import com.iplant.aps.serviceimpl.CoreServiceImpl;
import com.iplant.aps.utils.RetCode;
import com.iplant.aps.utils.aps.ExcelReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author PengYouWang
 * 2022-7-26 14:38:45
 */
@RestController
@RequestMapping("/api/SFCOutMaterialConfig")
public class SFCOutMaterialConfigController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(SFCOutMaterialConfigController.class);

    final
    SFCService wSFCService;

    public SFCOutMaterialConfigController(SFCService wSFCService) {
        this.wSFCService = wSFCService;
    }

    /**
     * 条件查询委外部件清单配置
     */
    @GetMapping("/All")
    public Object All(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            int wID = StringUtils.parseInt(request.getParameter("ID"));
            int wProductID = StringUtils.parseInt(request.getParameter("ProductID"));
            int wLineID = StringUtils.parseInt(request.getParameter("LineID"));
            int wSuplierID = StringUtils.parseInt(request.getParameter("SuplierID"));
            int wIsPartCode = StringUtils.parseInt(request.getParameter("IsPartCode"));
            int wPartID = StringUtils.parseInt(request.getParameter("PartID"));
            int wActive = StringUtils.parseInt(request.getParameter("Active"));
            String wMaterial = StringUtils.parseString(request.getParameter("Material"));

            int wOrderID = StringUtils.parseInt(request.getParameter("OrderID"));

            ServiceResult<List<SFCOutMaterialConfig>> wServiceResult =
                    wSFCService.SFC_QueryOutMaterialConfigList(wLoginUser,
                            wID, wProductID, wLineID, wSuplierID, wIsPartCode, wActive, wMaterial, wPartID, wOrderID);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 新增或更新
     */
    @PostMapping("/Update")
    public Object Update(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            if (!wParam.containsKey("data"))
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);

            SFCOutMaterialConfig wSFCOutMaterialConfig = CloneTool.Clone(wParam.get("data"),
                    SFCOutMaterialConfig.class);
            if (wSFCOutMaterialConfig == null)
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);

            ServiceResult<Integer> wServiceResult = wSFCService.SFC_UpdateOutMaterialConfig(wLoginUser,
                    wSFCOutMaterialConfig);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 批量新增或更新
     */
    @PostMapping("/UpdateAll")
    public Object UpdateAll(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            if (!wParam.containsKey("data"))
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);

            List<SFCOutMaterialConfig> wSFCOutMaterialConfigList = CloneTool.CloneArray(wParam.get("data"),
                    SFCOutMaterialConfig.class);
            if (wSFCOutMaterialConfigList == null || wSFCOutMaterialConfigList.size() <= 0)
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);

            // 新增权限控制
            if (wSFCOutMaterialConfigList.stream().anyMatch(p -> p.ID <= 0) && Configuration.readConfigString(
                    "EnableAccessControl", "config/config").equals("1")
                    && !CoreServiceImpl.getInstance().BMS_CheckPowerByAuthorityID(wLoginUser.CompanyID, wLoginUser.ID,
                            1610102, 0, 0)
                    .Info(Boolean.class)) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_CODE_UNROLE);
            }

            // 修改权限控制
            if (wSFCOutMaterialConfigList.stream().anyMatch(p -> p.ID > 0)
                    && wSFCOutMaterialConfigList.stream().anyMatch(p -> p.ID <= 0) && Configuration.readConfigString(
                    "EnableAccessControl", "config/config").equals("1")
                    && !CoreServiceImpl.getInstance().BMS_CheckPowerByAuthorityID(wLoginUser.CompanyID, wLoginUser.ID,
                            1610105, 0, 0)
                    .Info(Boolean.class)) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_CODE_UNROLE);
            }

            ServiceResult<Integer> wServiceResult = wSFCService.SFC_UpdateOutMaterialConfigList(wLoginUser,
                    wSFCOutMaterialConfigList);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 批量激活或禁用
     */
    @PostMapping("/Active")
    public Object Active(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            if (!wParam.containsKey("Active"))
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);

            int wActive = StringUtils.parseInt(wParam.get("Active"));

            // 启用权限控制
            if (wActive == 1 && Configuration.readConfigString("EnableAccessControl", "config/config").equals("1")
                    && !CoreServiceImpl.getInstance().BMS_CheckPowerByAuthorityID(wLoginUser.CompanyID, wLoginUser.ID,
                            1504004, 0, 0)
                    .Info(Boolean.class)) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_CODE_UNROLE);
            }

            //禁用权限控制
            if ((wActive == 0 || wActive == 2) && Configuration.readConfigString("EnableAccessControl", "config" +
                    "/config").equals("1")
                    && !CoreServiceImpl.getInstance().BMS_CheckPowerByAuthorityID(wLoginUser.CompanyID, wLoginUser.ID,
                            1504004, 0, 0)
                    .Info(Boolean.class)) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_CODE_UNROLE);
            }

            if (!wParam.containsKey("data"))
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);

            List<SFCOutMaterialConfig> wList = CloneTool.CloneArray(wParam.get("data"), SFCOutMaterialConfig.class);
            if (wList == null || wList.size() <= 0)
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);

            ServiceResult<Integer> wServiceResult = wSFCService.SFC_ActiveOutMaterialConfigList(wLoginUser, wList,
                    wActive);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 查询委外件BOM列表
     */
    @GetMapping("/OutBOMItemList")
    public Object OutBOMItemList(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            int wProductID = StringUtils.parseInt(request.getParameter("ProductID"));
            int wLineID = StringUtils.parseInt(request.getParameter("LineID"));
            int wPartID = StringUtils.parseInt(request.getParameter("PartID"));
            int wPartPointID = StringUtils.parseInt(request.getParameter("PartPointID"));
            String wMaterial = StringUtils.parseString(request.getParameter("Material"));
            if (wProductID <= 0 || wLineID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<List<MSSBOMItem>> wServiceResult = wSFCService.SFC_QueryOutBOMItemList(wLoginUser,
                    wProductID, wLineID, wPartID, wPartPointID, wMaterial);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 新增或更新子表
     */
    @PostMapping("/UpdateItem")
    public Object UpdateItem(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<>();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            SFCOutMaterialConfigItem wSFCOutMaterialConfigItem = CloneTool.Clone(wParam.get("data"),
                    SFCOutMaterialConfigItem.class);

            ServiceResult<Integer> wServiceResult = wSFCService.SFc_UpdateOutMaterialConfigItem(wLoginUser,
                    wSFCOutMaterialConfigItem);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 查询子表数据
     */
    @GetMapping("/ItemAll")
    public Object ItemAll(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            int wConfigID = StringUtils.parseInt(request.getParameter("ConfigID"));

            if (wConfigID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<List<SFCOutMaterialConfigItem>> wServiceResult =
                    wSFCService.SFC_QueryOutMaterialConfigItemList(wLoginUser,
                            wConfigID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 删除子表数据
     */
    @PostMapping("/DeleteItemList")
    public Object DeleteItemList(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<>();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            List<SFCOutMaterialConfigItem> wSFCOutMaterialConfigItemList = CloneTool.CloneArray(wParam.get("data"),
                    SFCOutMaterialConfigItem.class);

            if (wSFCOutMaterialConfigItemList == null || wSFCOutMaterialConfigItemList.size() <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = wSFCService.SFC_DeleteOutMaterialConfigItemList(wLoginUser,
                    wSFCOutMaterialConfigItemList);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 导入
     */
    @PostMapping("/Import")
    public Object Import(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            if (files.length == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "提示：没有要上传的Excel文件！");
            }

            ServiceResult<Integer> wServiceResult = new ServiceResult<>();
            ServiceResult<ExcelData> wExcelData = null;
            String wOriginalFileName = null;
            for (MultipartFile wMultipartFile : files) {
                wOriginalFileName = wMultipartFile.getOriginalFilename();

                assert wOriginalFileName != null;
                if (wOriginalFileName.contains("xlsx"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xlsx", 1000000);
                else if (wOriginalFileName.contains("xls"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xls", 1000000);

                assert wExcelData != null;
                if (StringUtils.isNotEmpty(wExcelData.FaultCode)) {
                    wResult = GetResult(RetCode.SERVER_CODE_ERR, wExcelData.FaultCode);
                    return wResult;
                }

                wServiceResult = wSFCService.SFC_ImportSFCOutMaterialConfig(wLoginUser, wExcelData.Result);

                if (!StringUtils.isEmpty(wServiceResult.FaultCode))
                    break;
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "导入成功!", null, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }
}
